package com.lj.common_web.config;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author luojing
 * @since 2024/7/26 17:57
 */
@Configuration
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer(JacksonProperties jacksonProperties) {
        if (jacksonProperties.getDateFormat() == null) {
            jacksonProperties.setDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        }
        final DateTimeFormatter formatter = DatePattern.createFormatter(jacksonProperties.getDateFormat());
        return builder -> {
            if (jacksonProperties.getDefaultPropertyInclusion() != null) {
                builder.serializationInclusion(jacksonProperties.getDefaultPropertyInclusion());
            }
            if (jacksonProperties.getTimeZone() != null) {
                builder.timeZone(jacksonProperties.getTimeZone());
            }
            builder.simpleDateFormat(jacksonProperties.getDateFormat())
                    // Long类型返回给前端时，页面会因为数值过大会丢失精度
                    .serializerByType(Long.class, ToStringSerializer.instance)
                    .serializerByType(Long.TYPE, ToStringSerializer.instance)
                    // LocalDateTime 返回给前端会变成数组
                    .serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter))
                    .deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }

}
